package com.apes.fn.server.productRequireManage.model;

import com.alibaba.fastjson.JSONObject;
import com.apes.framework.api.DomainService;
import com.apes.framework.util.MapUtil;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.product.model.ProductUom;
import com.apes.scm.masterdata.product.repository.ProductUomRepository;
import lombok.Data;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public abstract class ReplenishmentBusinessImpAbstract extends DomainService implements ReplenishmentBusinessImp {

    @Override
    public Map sendOrder(JSONObject getJO) {
        return new HashMap();
    }

    @Override
    public JSONObject sumRequireItem(JSONObject getJO) {
        return null;
    }

    // 获取可用数
    public double obtainStockUsableQty(String reception, String fLocationId, String productId, String subCompanyId) {
        String export = invoke("scm.transferProductService.accordLCompanyChangeOperation", MapUtil.mapper("id", fLocationId));
        List<String> supplierIds = invoke("scm.transferProductService.accordOperationFindSupplier", MapUtil.mapper("export", export, "reception", reception));
        Map stock = invoke("scm.transferProductService.accordOperationStock",
                MapUtil.mapper("fLocationId", fLocationId, "productId", productId, "supplierIds", supplierIds, "export", export, "reception", reception));

        if ("001073".equals(export) && !"001073".equals(reception) && stock.isEmpty()) {
            if (StringUtils.hasText(subCompanyId)) {
                throw new RuntimeException("请确认 "+ fLocationId +" 仓库的【"+ productId +"】商品是否有库存，\r\n" + subCompanyId + " 公司是否有配置【采购合同、平台协议合同、调拨范围】");
            } else {
                throw new RuntimeException("请确认 "+ fLocationId +" 仓库是否有库存，\r\n" + productId + " 商品的要货仓库公司是否有配置【采购合同、平台协议合同、调拨范围】");
            }
        } else if (stock.isEmpty()) {
            if (supplierIds.contains("existsSupplierNull")) throw new RuntimeException(fLocationId + "仓库未找到可用库存, 请检查【"+ productId +"】商品 \n\r 库存是否还有可用数、\n\r 批次是否有结存、\n\r 发货仓批次供应商是否有有效合同");
            throw new RuntimeException(fLocationId + "仓库未找到可用库存, 请检查【"+ productId +"】商品库存是否还有可用数、批次是否有结存");
        }

        ProductUom minFactorUom = getBean(ProductUomRepository.class).findByProductIdFactorMin(productId);
        ProductUom dumpUom = getBean(ProductUomRepository.class).findByProductId(productId);
        if (dumpUom.getFactor() != minFactorUom.getFactor()) {
            return Math.floor(minFactorUom.computeQty(Double.parseDouble(stock.get("USABLE_QTY").toString()), dumpUom, false));
        }
        return Double.parseDouble(stock.get("USABLE_QTY").toString());
    }
}
